package com.cby.android.base.handler

import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.os.Message
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.cby.android.base.R
import android.os.Looper





/**
 * @description: 子线程创建handler
 *
 * @author ChenBaoyang
 * @date 2021/10/13 14:42
 */
class HandlerThreadActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_handler)
        val textView = findViewById<View>(R.id.tv) as TextView
        textView.text = "HandlerThreadActivity"

        val handlerThread = HandlerThread("HandlerThread")
        handlerThread.start()

        val mHandler: Handler = object : Handler(handlerThread.looper) {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                //子线程
                Log.d("HandlerThreadActivity", "uiThread2------" + Thread.currentThread())
            }
        }
        //主线程
        Log.d("HandlerThreadActivity", "uiThread1------" + Thread.currentThread())
        mHandler.sendEmptyMessage(1)

    }

    private fun createChildThreadHandler() {
        val thread = MyThread()
        thread.start()
    }

    class MyThread : Thread() {
        var childLooper: Looper? = null
        var handler: Handler? = null

        override fun run() {
            Looper.prepare() //创建与当前线程相关的Looper
            childLooper = Looper.myLooper() //获取当前线程的Looper对象
            Log.d("HandlerThreadActivity", "Thread3------" + currentThread())
            handler = Handler(childLooper!!)
            Looper.loop() //调用此方法，消息才会循环处理
        }
    }

    fun onCreateThreadHandler(view: View) {
        createChildThreadHandler()
    }
}